<template>
  <el-card class="box-card">
    <el-tabs v-model="state.activeName" v-loading="state.tableData.loading">
      <el-tab-pane label="基本信息" name="basic">
        <el-form ref="BasicInfoForm" :model="state.info" :rules="rulesRules" label-width="120px">
          <el-card>
            <el-row :gutter="20">
              <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                <el-form-item label="表名称：" prop="tableName" size="default">
                  <el-input placeholder="请输入仓库名称" v-model="state.info.tableName" />
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                <el-form-item label="实体类名称：" prop="className" size="default">
                  <el-input placeholder="请输入" v-model="state.info.className" />
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                <el-form-item label="作  者：" prop="functionAuthor" size="default">
                  <el-input placeholder="请输入" v-model="state.info.functionAuthor" />
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
              </el-col>
              <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                <el-form-item label="表描述：" prop="tableComment" size="default">
                  <el-input placeholder="请输入表描述信息" v-model="state.info.tableComment" type="textarea" :rows="3" />
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                <el-form-item label="备注：" prop="remark" size="default">
                  <el-input type="textarea" :rows="3" v-model="state.info.remark"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-card>
        </el-form>
      </el-tab-pane>
      <el-tab-pane label="字段信息" name="columnInfo">
        <el-table ref="DragTable" :data="state.columns" row-key="columnId" :max-height="state.tableHeight">
          <el-table-column label="序号" type="index" width="80" />
          <el-table-column label="字段列名" prop="columnName" width="120" show-overflow-tooltip />
          <el-table-column label="字段描述" width="120">
            <template #default="scope">
              <el-input v-model="scope.row.columnComment"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="物理类型" prop="columnType" width="120" show-overflow-tooltip />
          <el-table-column label="Java类型" width="120">
            <template #default="scope">
              <el-select v-model="scope.row.javaType">
                <el-option label="Long" value="Long" />
                <el-option label="String" value="String" />
                <el-option label="Integer" value="Integer" />
                <el-option label="Double" value="Double" />
                <el-option label="BigDecimal" value="BigDecimal" />
                <el-option label="Date" value="Date" />
                <el-option label="Boolean" value="Boolean" />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="java属性" width="100">
            <template #default="scope">
              <el-input v-model="scope.row.javaField"></el-input>
            </template>
          </el-table-column>

          <el-table-column label="插入" width="80">
            <template #default="scope">
              <el-checkbox true-label="1" false-label="0" v-model="scope.row.isInsert"></el-checkbox>
            </template>
          </el-table-column>
          <el-table-column label="编辑" width="80">
            <template #default="scope">
              <el-checkbox true-label="1" false-label="0" v-model="scope.row.isEdit"></el-checkbox>
            </template>
          </el-table-column>
          <el-table-column label="列表" width="80">
            <template #default="scope">
              <el-checkbox true-label="1" false-label="0" v-model="scope.row.isList"></el-checkbox>
            </template>
          </el-table-column>
          <el-table-column label="查询" width="80">
            <template #default="scope">
              <el-checkbox true-label="1" false-label="0" v-model="scope.row.isQuery"></el-checkbox>
            </template>
          </el-table-column>
          <el-table-column label="查询方式" width="120">
            <template #default="scope">
              <el-select v-model="scope.row.queryType">
                <el-option label="=" value="EQ" />
                <el-option label="!=" value="NE" />
                <el-option label=">" value="GT" />
                <el-option label=">=" value="GE" />
                <el-option label="<" value="LT" />
                <el-option label="<=" value="LE" />
                <el-option label="LIKE" value="LIKE" />
                <el-option label="BETWEEN" value="BETWEEN" />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="必填" width="80">
            <template #default="scope">
              <el-checkbox true-label="1" false-label="0" v-model="scope.row.isRequired"></el-checkbox>
            </template>
          </el-table-column>
          <el-table-column label="显示类型" width="120">
            <template #default="scope">
              <el-select v-model="scope.row.htmlType">
                <el-option label="文本框" value="input" />
                <el-option label="文本域" value="textarea" />
                <el-option label="下拉框" value="select" />
                <el-option label="单选框" value="radio" />
                <el-option label="复选框" value="checkbox" />
                <el-option label="日期控件" value="datetime" />
                <el-option label="图片上传" value="imageUpload" />
                <el-option label="文件上传" value="fileUpload" />
                <el-option label="富文本控件" value="editor" />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="字典类型" width="120">
            <template #default="scope">
              <el-select v-model="scope.row.dictType" clearable filterable placeholder="请选择">
                <el-option v-for="dict in state.dictOptions" :key="dict.dictType" :label="dict.dictName"
                  :value="dict.dictType">
                  <span style="float: left">{{ dict.dictName }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">{{ dict.dictType }}</span>
                </el-option>
              </el-select>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
      <el-tab-pane label="生成信息" name="genInfo">
        <el-form ref="GenInfoForm" :rules="genInfoFormRules" :model="state.info" label-width="150px">
          <el-row :gutter="35">
            <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
              <el-form-item prop="tplCategory">
                <template #label>生成模板</template>
                <el-select v-model="state.info.tplCategory" @change="tplSelectChange">
                  <el-option label="单表（增删改查）" value="crud" />
                  <el-option label="树表（增删改查）" value="tree" />
                  <!--<el-option label="主子表（增删改查）" value="sub" />-->
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
              <el-form-item prop="packageName">
                <template #label>
                  <el-tooltip content="生成在哪个java包下，例如 com.ruoyi.system" placement="top">
                    <p><span>生成包路径</span>&nbsp;&nbsp;<el-icon><ele-QuestionFilled /></el-icon></p>
                  </el-tooltip>
                </template>
                <el-input v-model="state.info.packageName" />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
              <el-form-item prop="moduleName">
                <template #label>
                  <el-tooltip content="可理解为子系统名，例如 system" placement="top">
                    <p><span>生成模块名</span>&nbsp;&nbsp;<el-icon><ele-QuestionFilled /></el-icon></p>
                  </el-tooltip>
                </template>
                <el-input v-model="state.info.moduleName" />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
              <el-form-item prop="businessName">
                <template #label>
                  <el-tooltip content="可理解为功能英文名，例如 user" placement="top">
                    <p><span>生成业务名</span>&nbsp;&nbsp;<el-icon><ele-QuestionFilled /></el-icon></p>
                  </el-tooltip>
                </template>
                <el-input v-model="state.info.businessName" />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
              <el-form-item prop="functionName">
                <template #label>
                  <el-tooltip content="用作类描述，例如 用户" placement="top">
                    <p><span>生成功能名</span>&nbsp;&nbsp;<el-icon><ele-QuestionFilled /></el-icon></p>
                  </el-tooltip>
                </template>
                <el-input v-model="state.info.functionName" placeholder="请输入类描述" />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
              <el-form-item>
                <template #label>
                  <el-tooltip content="分配到指定菜单下，例如 系统管理" placement="top">
                    <p><span>上级菜单</span>&nbsp;&nbsp;<el-icon><ele-QuestionFilled /></el-icon></p>
                  </el-tooltip>
                </template>
                <el-tree-select v-model="state.info.parentMenuId" check-strictly :data="state.menuOptions"
                  :props="{ value: 'menuId', label: 'menuName', children: 'children' }" placeholder="请选择系统菜单" />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
              <el-form-item prop="genType">
                <template #label>
                  <el-tooltip content="默认为zip压缩包下载，也可以自定义生成路径" placement="top">
                    <p><span>生成代码方式</span>&nbsp;&nbsp;<el-icon><ele-QuestionFilled /></el-icon></p>
                  </el-tooltip>
                </template>
                <el-radio v-model="state.info.genType" label="0">zip压缩包</el-radio>
                <el-radio v-model="state.info.genType" label="1">自定义路径</el-radio>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20" v-if="state.info.genType == '1'">
              <el-form-item prop="genPath">
                <template #label>
                  <el-tooltip content="填写磁盘绝对路径，若不填写，则生成到当前Web项目下" placement="top">
                    <p><span>自定义路径</span>&nbsp;&nbsp;<el-icon><ele-QuestionFilled /></el-icon></p>
                  </el-tooltip>
                </template>
                <el-input v-model="state.info.genPath">
                  <template #append>
                    <el-dropdown>
                      <el-button type="primary">
                        最近路径快速选择
                        <i class="el-icon-arrow-down el-icon--right"></i>
                      </el-button>
                      <template #dropdown>
                        <el-dropdown-menu>
                          <el-dropdown-item @click="state.info.genPath = '/';">恢复默认的生成基础路径</el-dropdown-item>
                        </el-dropdown-menu>
                      </template>
                    </el-dropdown>
                  </template>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <template v-if="state.info.tplCategory == 'tree'">
            <h4 class="form-header">其他信息</h4>
            <el-row :gutter="35" v-show="state.info.tplCategory == 'tree'">
              <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                <el-form-item>
                  <template #label>
                    <el-tooltip content="树显示的编码字段名， 如：dept_id" placement="top">
                      <p><span>树编码字段</span>&nbsp;&nbsp;<el-icon><ele-QuestionFilled /></el-icon></p>
                    </el-tooltip>
                  </template>
                  <el-select v-model="state.info.treeCode" placeholder="请选择">
                    <el-option v-for="(column, index) in state.info.columns" :key="index"
                      :label="column.columnName + '：' + column.columnComment" :value="column.columnName"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                <el-form-item>
                  <template #label>
                    <el-tooltip content="树显示的父编码字段名， 如：parent_Id" placement="top">
                      <p><span>树父编码字段</span>&nbsp;&nbsp;<el-icon><ele-QuestionFilled /></el-icon></p>
                    </el-tooltip>
                  </template>
                  <el-select v-model="state.info.treeParentCode" placeholder="请选择">
                    <el-option v-for="(column, index) in state.info.columns" :key="index"
                      :label="column.columnName + '：' + column.columnComment" :value="column.columnName"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                <el-form-item>
                  <template #label>
                    <el-tooltip content="树节点的显示名称字段名， 如：dept_name" placement="top">
                      <p><span>树名称字段</span>&nbsp;&nbsp;<el-icon><ele-QuestionFilled /></el-icon></p>
                    </el-tooltip>
                  </template>
                  <el-select v-model="state.info.treeName" placeholder="请选择">
                    <el-option v-for="(column, index) in state.info.columns" :key="index"
                      :label="column.columnName + '：' + column.columnComment" :value="column.columnName"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </template>
          <template v-if="state.info.tplCategory == 'sub'">
            <h4 class="form-header">关联信息</h4>
            <el-row :gutter="35">
              <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                <el-form-item>
                  <template #label>
                    <el-tooltip content="关联子表的表名， 如：sys_user" placement="top">
                      <p><span>关联子表的表名</span>&nbsp;&nbsp;<el-icon><ele-QuestionFilled /></el-icon></p>
                    </el-tooltip>
                  </template>
                  <el-select v-model="state.info.subTableName" placeholder="请选择" @change="subSelectChange">
                    <el-option v-for="(table, index) in state.tables" :key="index"
                      :label="table.tableName + '：' + table.tableComment" :value="table.tableName"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                <el-form-item>
                  <template #label>
                    <el-tooltip content="子表关联的外键名， 如：user_id" placement="top">
                      <p><span>子表关联的外键名</span>&nbsp;&nbsp;<el-icon><ele-QuestionFilled /></el-icon></p>
                    </el-tooltip>
                  </template>
                  <el-select v-model="state.info.subTableFkName" placeholder="请选择">
                    <el-option v-for="(column, index) in state.subColumns" :key="index"
                      :label="column.columnName + '：' + column.columnComment" :value="column.columnName"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </template>
        </el-form>
      </el-tab-pane>
    </el-tabs>
    <el-form label-width="100px">
      <div style="text-align: center;margin-left:-100px;margin-top:10px;">
        <el-button type="primary" @click="submitForm()" v-auths="['tool:gen:edit']">提交</el-button>
        <el-button @click="close()">返回</el-button>
      </div>
    </el-form>
  </el-card>
</template>

<script setup name="toolGenEditTable" lang="ts">
import { ref, onMounted, reactive, watch } from 'vue';
import { useGenApi } from '/@/api/tool/gen';
import { useDictType } from '/@/api/system/dict/type';
import { ElMessage } from 'element-plus';
import { useRoute } from 'vue-router';
import router from '/@/router';
import { handleTree } from '/@/utils/tool';
import { useMenu } from '/@/api/system/menu';


const BasicInfoForm = ref();
const GenInfoForm = ref();
const DragTable = ref();

const state = reactive({
  tableData: {
    data: [],
    total: 0,
    loading: false,
  },
  menuOptions: [] as any[],
  subColumns: [] as any[],
  activeName: 'basic',
  tableHeight: document.documentElement.scrollHeight - 245 + 'px',
  tables: [] as any[],
  columns: [] as any[],
  dictOptions: [] as any[],
  info: {} as GenInfo,
  tableId: ''
})

// 表单校验
const rulesRules = ref({
  tableName: [{ required: true, message: "请输入表名称", trigger: "blur" }],
  tableComment: [{ required: true, message: "请输入表描述", trigger: "blur" }],
  className: [{ required: true, message: "请输入实体类名称", trigger: "blur" }],
  functionAuthor: [{ required: true, message: "请输入作者", trigger: "blur" }]
});
// 表单校验
const genInfoFormRules = ref({
  tplCategory: [{ required: true, message: "请选择生成模板", trigger: "blur" }],
  packageName: [{ required: true, message: "请输入生成包路径", trigger: "blur" }],
  moduleName: [{ required: true, message: "请输入生成模块名", trigger: "blur" }],
  businessName: [{ required: true, message: "请输入生成业务名", trigger: "blur" }],
  functionName: [{ required: true, message: "请输入生成功能名", trigger: "blur" }]
});



const getTableData = async () => {
  try {
    state.tableData.loading = true;
    const [res, dictRes, menuRes] = await Promise.all([
      await useGenApi().getGenTable(state.tableId),
      await useDictType().optionselect(),
      await useMenu().listMenu(),
    ]);
    if (res.code === 200) {
      state.columns = res.data.rows;
      state.info = res.data.info;
      state.tables = res.data.tables;
    } else {
      ElMessage.error(res.msg);
    }
    state.dictOptions = dictRes.data;
    state.menuOptions = handleTree(menuRes.data, 'menuId');
    state.tableData.loading = false;
  } catch (error) {
    Promise.reject(error);
  }
};



const submitForm = async () => {
  try {
    state.tableData.loading = true;
    await Promise.all([BasicInfoForm.value.validate(), GenInfoForm.value.validate()]);
    const genTable = {
      ...state.info,
      columns: state.columns,
      params: {
        treeCode: state.info.treeCode,
        treeName: state.info.treeName,
        treeParentCode: state.info.treeParentCode,
        parentMenuId: state.info.parentMenuId,
      },
    };
    const res = await useGenApi().updateGenTable(genTable);
    if (res.code === 200) {
      ElMessage.success(res.msg);
      state.tableData.loading = false;
      router.push({ path: '/gen' });
    } else {
      state.tableData.loading = false;
      ElMessage.error(res.msg);
    }
  } catch (error) {
    state.tableData.loading = false;
    Promise.reject(error);
  }
};


/** 关闭按钮 */
const subSelectChange = () => {
  state.info.subTableFkName = "";
}
/**
 * 模板选择
 * @param value
 */
const tplSelectChange = (value: string) => {
  if (value !== "sub") {
    state.info.subTableName = "";
    state.info.subTableFkName = "";
  }
}
/**
 * 设置子表字段
 * @param value
 */
const setSubTableColumns = (value: any) => {
  for (var item in state.tables) {
    const name = state.tables[item].tableName;
    if (value === name) {
      state.subColumns = state.tables[item].columns;
      break;
    }
  }
  if (!state.subColumns) {
    state.subColumns = [];
  }
}


/**
 * 关闭按钮
 */
const close = () => {
  router.push({ path: '/gen' });
}

/**
 * 监听子表名变化
 */
watch(() => state.info.subTableName, (val: any) => {
  setSubTableColumns(val);
});

/**
 * 监听表名变化
 */
onMounted(() => {
  /**
   * 接收Route传递的参数
   */
  const route = useRoute();
  state.tableId = route.query.tableId as string;
  getTableData();
});

</script>
